/*
 * @Descripttion: 
 * @Author: zhangchong zc16607@gmail.com
 * @Date: 2023-03-02 18:42:23
 * @LastEditors: zhangchong zc16607@gmail.com
 * @LastEditTime: 2024-02-08 14:15:39
 */
const { getKey } = require('../utils/fileDb')
const { sm4Decrypt, md5, getFullUrl, sm4Encrypt } = require('../utils/index')
const commonRes = require('../utils/commonRes')
const commonNasReq = require('../utils/commonNasReq').commonReq
const got = require('../utils/got')
const cheerio = require('cheerio')
const fs = require('fs')

async function aa79b839dd77a5ce6(res, baseUrl, resData) {
  let $ = cheerio.load(resData)


  let trArr = $('.s-table-body-item>.torrent-item')
  let trData = trArr.map((i, tr) => {
    let trEle = $(tr)

    let title = trEle.find('.torrent-info>.torrent-title').text()
    let nameOrigin = trEle.find('.torrent-info>.torrent-subtitle').text()
    let name = nameOrigin.split('|')[0]
    let languageOrigin = nameOrigin.match(/[【|[].+?[\]|】]/g) // 字幕和语言
    let language = languageOrigin && languageOrigin.join().replace(/\[|\]|【|】/g, '') || ''
    let contentOriginUrl = trEle.find('.torrent-info>.torrent-title>a').attr('href')
    let contentUrl = sm4Encrypt(getFullUrl(baseUrl, contentOriginUrl))

    let tagsOrigin = trEle.find('.torrent-info>.torrent-tags>a').map((s, span) => $(span).text()).get()
    let tags = tagsOrigin.join()
    let freeEle = trEle.find('.twoupfree,.free')
    let price = ''
    let priceTime = ''
    if (freeEle.length) {
      price = freeEle.prev().text()
      priceTime = freeEle.children('span').text()
    }
    let score = ''
    let itemId = contentOriginUrl.match(/id\=(\d+)/)[1]
    let downUrl = itemId ? `download.php?id=${itemId}` : ''
    downUrl = getFullUrl(baseUrl, downUrl)
    let survivalTime = trEle.find('.torrent-when').text().replace('\n', '').trim()
    let size = trEle.find('.torrent-size').text().replace('\n', '').trim()
    let distribute = trEle.find('.torrent-seeders').text().replace('\n', '').trim()
    let downloads = trEle.find('.torrent-leechers').text().replace('\n', '').trim()
    let completes = trEle.find('.torrent-snatches').text().replace('\n', '').trim()
    let publisher = ''

    return {
      title,
      name,
      language,
      posterImg: '', // tr暂时取不到
      contentUrl, // 内容url
      downUrl,  // 
      tags,
      price,
      priceTime,
      score,  // 评分
      survivalTime, // 存活时间
      size,
      distribute,   // 种子数
      downloads,  // 下载数
      completes, // 完成数
      publisher,  // 发布者
    }
  }).get()

  return trData
}

async function a8712a1c3f90ab15d(res, baseUrl, resData) {
  let $ = cheerio.load(resData)


  let trArr = $('table.torrents>tbody>tr')
  let trData = trArr.slice(1).map((i, tr) => {
    let trEle = $(tr)
    let left1 = trEle.find('table.torrentname>tbody>tr>td:nth-child(1)')
    let left2 = trEle.find('table.torrentname>tbody>tr>td:nth-child(2)')
    let left3 = trEle.find('table.torrentname>tbody>tr>td:nth-child(3)')

    let lens = trEle.find('table.torrentname>tbody>tr>td').length
    if (lens === 2) {
      let temp = left2
      left2 = left1
      left3 = temp
    }

    let title = left2.children('a').first().text()
    let nameOrigin = left2.first().contents().last().text()
    let name = nameOrigin.split('|')[0] // 副标题
    let posterImg = getFullUrl(baseUrl, left1.find('img').attr('src'))


    let languageOrigin = nameOrigin.match(/[【|[].+?[\]|】]/g) // 字幕和语言
    let language = languageOrigin && languageOrigin.join().replace(/\[|\]|【|】/g, '') || ''
    let contentUrl = left2.children('a').first().attr('href')
    contentUrl = sm4Encrypt(getFullUrl(baseUrl, contentUrl))

    let tagsOrigin = left2.children('a.dib').map((s, span) => $(span).text()).get()
    let tags = tagsOrigin.join()
    let price = left2.find('font.promotion').text()
    let priceTime = left2.find('font.promotion').next().text()

    // let score = left2.text().split('\n').map(s => parseFloat(s)).join()
    let downUrl = left3.find('i.download').parent().attr('href')
    downUrl = getFullUrl(baseUrl, downUrl)
    let survivalTime = trEle.find('td:nth-child(5)').text().replace('\n', '')
    let size = trEle.find('td:nth-child(6)').text().replace('\n', '')
    let distribute = trEle.find('td:nth-child(7)').text().replace('\n', '')
    let downloads = trEle.find('td:nth-child(8)').text().replace('\n', '')
    let completes = trEle.find('td:nth-child(9)').text().replace('\n', '')
    let publisher = trEle.find('td:nth-child(11)').text().replace('\n', '')



    return {
      title,
      name,
      language,
      posterImg, // tr暂时取不到
      contentUrl, // 内容url
      downUrl,  // 
      tags,
      price,
      priceTime,
      score: '',  // 评分
      survivalTime, // 存活时间
      size,
      distribute,   // 种子数
      downloads,  // 下载数
      completes, // 完成数
      publisher,  // 发布者
    }
  }).get()

  return trData
}


async function a2f447c3c40cb98a3(res, baseUrl, resData) {
  let $ = cheerio.load(resData)


  let trArr = $('table.torrents>tbody>tr')
  let trData = trArr.slice(1).map((i, tr) => {
    let trEle = $(tr)
    let left1 = trEle.find('table.torrentname>tbody>tr>td:nth-child(1)')
    let left2 = trEle.find('table.torrentname>tbody>tr>td:nth-child(2)')
    let left3 = trEle.find('table.torrentname>tbody>tr>td:nth-child(3)')

    let lens = trEle.find('table.torrentname>tbody>tr>td').length
    if (lens === 2) {
      let temp = left2
      left2 = left1
      left3 = temp
    }

    let title = left2.children('a').first().text()
    let nameOrigin = left2.first().contents().last().text()
    let name = nameOrigin.split('|')[0] // 副标题
    if (!name) name = title // 无副标题，则使用title
    let posterImg = ''
    if (lens === 3) {
      posterImg = getFullUrl(baseUrl, left1.find('img').attr('src'))
    }



    let languageOrigin = nameOrigin.match(/[【|[].+?[\]|】]/g) // 字幕和语言
    let language = languageOrigin && languageOrigin.join().replace(/\[|\]|【|】/g, '') || ''
    let contentUrl = left2.children('a').first().attr('href')
    contentUrl = sm4Encrypt(getFullUrl(baseUrl, contentUrl))

    let tagsOrigin = left2.children('a.dib').map((s, span) => $(span).text()).get()
    let tags = tagsOrigin.join()
    let price = left2.find('.pro_free').attr('title')
    let priceTime = left2.find('.pro_free').next().text()

    let score = left3.text().split('\n').map(s => parseFloat(s)).join()
    let downUrl = left3.find('a').filter(function (i, el) {
      return $(this).attr('href').includes('download.php')
    }).attr('href')
    downUrl = getFullUrl(baseUrl, downUrl)
    let survivalTime = trEle.find('td:nth-child(4)').text().replace('\n', '')
    let size = trEle.find('td:nth-child(5)').text().replace('\n', '')
    let distribute = trEle.find('td:nth-child(6)').text().replace('\n', '')
    let downloads = trEle.find('td:nth-child(7)').text().replace('\n', '')
    let completes = trEle.find('td:nth-child(8)').text().replace('\n', '')
    let publisher = trEle.find('td:nth-child(10)').text().replace('\n', '')



    return {
      title,
      name,
      language,
      posterImg, // tr暂时取不到
      contentUrl, // 内容url
      downUrl,  // 
      tags,
      price,
      priceTime,
      score,  // 评分
      survivalTime, // 存活时间
      size,
      distribute,   // 种子数
      downloads,  // 下载数
      completes, // 完成数
      publisher,  // 发布者
    }
  }).get()

  return trData
}


class Content {
  // 获取板块列表
  static async plate(req, res) {
    let { siteid, plateid } = req.params
    let siteArr = getKey('siteRes')
    let siteData = siteArr.filter(site => site.sid == siteid)[0]
    if (!siteData) return commonRes(res, '')
    const cookie = sm4Decrypt(siteData.cookie)
    let plateData = siteData.plates.filter(pl => pl.pid == plateid)[0]
    if (!(cookie && plateData && plateData.purl)) return commonRes(res, null, { message: '站点信息不全', status: 'error' })

    let plateResData = ''
    try {
      plateResData = await got(plateData.purl, {
        headers: {
          cookie
        }
      }).text()
    } catch (e) {
      // 判断状态码是否是403
      if (e.response && e.response.statusCode === 403) {
        return commonRes(res, null, { message: 'cookie已失效', status: 'error' })
      }
      return commonRes(res, null, { message: (e.response ? e.response.statusMessage : e), status: 'error' })
    }

    let pu = new URL(plateData.purl)
    let ha = pu.host.split('.')
    let baseUrl = pu.origin
    let u, cdata, mu = ''
    ha.length === 3 ? u = ha[1] : ha.length === 2 ? u = ha[0] : ''
    if (u) {
      // 部分md5结果是数字开头，因此加一个a
      mu = 'a' + md5(u).slice(8, 24)
      switch (mu) {
        case 'aa79b839dd77a5ce6':
          cdata = await aa79b839dd77a5ce6(res, baseUrl, plateResData)
          break
        case 'a8712a1c3f90ab15d':
          cdata = await a8712a1c3f90ab15d(res, baseUrl, plateResData)
          break
        case 'a2f447c3c40cb98a3':
          cdata = await a2f447c3c40cb98a3(res, baseUrl, plateResData)
          break
        default:
          cdata = await a2f447c3c40cb98a3(res, baseUrl, plateResData)
      }
    } else {
      // 没匹配到url
    }

    commonRes(res, cdata)
  }

  // 获取文章的详情
  static async detail(req, res) {
    let { siteid, plateid, aurl } = req.params
    let siteArr = getKey('siteRes')
    let siteData = siteArr.filter(site => site.sid == siteid)[0]
    let plateData = siteData.plates.filter(pl => pl.pid == plateid)[0]
    const cookie = sm4Decrypt(siteData.cookie)
    let articleUrl = sm4Decrypt(decodeURIComponent(aurl))

    let data = await req.cache.tryGet(aurl, async () => {
      let doc = await got(articleUrl, {
        headers: {
          cookie,
          'referer': plateData.purl
        }
      }).text()
      let $ = cheerio.load(doc)
      let descRaw = $('#kdescr').html()
      // 如果有dmm信息，添加dmm信息
      let dmmType = $('.dmm_type')
      let dmmText = $('.dmm_text')
      let dmmPic = $('.dmm_pic')
      if (dmmPic) {
        // 如果有dmm图片，显示在最前面
        descRaw = dmmPic.html() + descRaw + dmmType.html() + dmmText.html()
      } else {
        descRaw = descRaw
      }
      // 处理html中图片的相对路径
      const baseUrl = new URL(articleUrl).origin + '/'; // 定义基础路径
      const bigImgResult = descRaw.replace(/\.thumb\.jpg/g, '')
      const dmmBigImgResult = bigImgResult.replace(/<img src="[^"]+" onclick="Previewurl\('([^']+)'\)"/g, '<img src="$1"')
      const regex = /(<img[\s\S]*?src=")(?!http)(.*?)(["\s][\s\S]*?>)/gi; // 匹配 img 标签中的 src 属性，但排除以 http 开头的绝对路径
      let result = dmmBigImgResult.replace(regex, `$1${baseUrl}$2$3`); // 将相对路径替换为绝对路径
      let script = `
      <script>
        function Previewurl(url){
          let imgWrap = document.getElementById('imgWrap')
          let wrap = document.createElement('div')
          if(!imgWrap){
            wrap.id = 'imgWrap'
            wrap.style.width = '100vw'
            wrap.style.position = "fixed"
            wrap.style.left = "50%"
            wrap.style.top = "50%"
            wrap.style.transform = "translate(-50%, -50%)"
            wrap.style.zIndex = "999"
            wrap.style.height = "auto"
            wrap.style.display = "flex"
            wrap.style.justifyContent = "center"
            wrap.onclick = Return
          }else{
              imgWrap.style.display = 'flex'
          }
          let fanlWrap = imgWrap || wrap
          fanlWrap.innerHTML = "<img src=" + url + " />"
          if(!imgWrap) document.body.appendChild(fanlWrap)
        }
        function Return(){
          document.getElementById('imgWrap').style.display = "none"
        }
      </script>
      `;
      result += script
      return result
    })

    commonRes(res, data)
  }

  // 订阅
  static async subscribe(req, res) {

    commonRes(res, {})
  }

  // 下载
  static async download(req, res) {

    const { url, title, description } = req.body
    // 如果是报500，应该是没识别到媒体信息
    try {
      let nastool = getKey('nastool')
      let data = await commonNasReq('/download/item', '', { enclosure: url, title, description, uploadvolumefactor: '1.0', downloadvolumefactor: '1.0', dl_dir: nastool.downloadPath || '' })
      return commonRes(res, {}, { message: '添加下载成功！' })
    } catch {
      return commonRes(res, '', { status: 'error', message: '请求失败' })
    }

  }

  // 收藏
  static async collect(req, res) {

    commonRes(res, {})
  }
}



module.exports = Content